<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>超帅组合的qq网页</title>
<link rel="stylesheet" href="css/qq.css">
<link rel="stylesheet" type="text/css" href="css/qq.css">
<link rel="stylesheet" href="css/zhuy.css" />
</head>
<style>
	.contact-enevt2{
		 float: right;
		 width: 10%;
		 height: 100%;
		 border-radius: 50px;
		 background-color: white;
		 color: #12b7f5;
		 border: 1px solid #f5f5f5;
		 box-shadow: 1px 1px 5px #f5f5f5, -1px -1px 5px #f5f5f5;
		 margin-right: 5%;
		 margin-top:-1%;
	}
	.contact-enevt2:hover{
		 background-color: #ddd;
	}
</style>
<script type="text/javascript">
	var ws ="";
	//let ip = "localhost:8080";//测试时使用，实际使用需要用服务器ip
	let ip = "172.20.10.4";
	var ws_url = "ws://localhost:8080/chatBlog/ChatrecordsRoom/${sessionScope.loginUser.account}";
	var me = "${sessionScope.loginUser.account}";
	var myHeadimg = "${sessionScope.loginUser.avatar}";
	var sendTo = null;
	var nickName = "${sessionScope.loginUser.nickName}";
	var user_id = "${sessionScope.loginUser.userId}";
	document.addEventListener('keydown',function(event) {
	    if (event.key === 'Enter') {
	    	//调用发消息方法
	    	event.preventDefault()
	        ws_sendMsg();
	    	console.log("发送成功");
	    }
	});
	ws_connect();
	/* $(function(){
		//页面加载后，获取一个 websocket连接
		ws_connect();
	}); */
	function ws_connect(){

	         if ('WebSocket' in window) {
	             ws = new WebSocket(ws_url);
	         } else if ('MozWebSocket' in window) {
	             ws = new MozWebSocket(ws_url);
	         } else {
	             Console.log('Error: WebSocket is not supported by this browser.');
	             return;
	         }

	         ws.onopen = function () {
	             console.log('Info: WebSocket connection opened.');
	             
	         };

	         ws.onclose = function () {
	              console.log('Info: WebSocket closed.');
	          };

	          ws.onmessage = function (message) {
	        	  let chatRecord = JSON.parse(message.data);
	        	  let talkWith = friendAccount;
	        	  //判断当前正在聊天的人 是否 和 服务器推送的消息 的发信人一样
	        	  //收到对方发的消息 或者自己发送给服务器的消息
	        	  if(talkWith == chatRecord.myAccount || me == chatRecord.myAccount){
	        		  let html = $('#chat-messages').html();
	        		  let messageClass = chatRecord.myAccount === me 
			            ? 'message sent' 
			            : 'message received';
	        		  if(messageClass == 'message sent'){//我的自己
	        			  html += `
		  			            <div class='${"${messageClass}"}'>
		  			                <div class="message-avatar">
		  			                </div>
		  			                <div class="message-content">
		  			                    <div class="message-name">${"${chatRecord.myAccount}"}</div>
		  			                    <div class="message-bubble">${"${chatRecord.message}"}</div>
		  			                    <div class="message-time">${"${chatRecord.messageDate}"}</div>
		  			                </div>
		  			            </div>`;
	        		  }else if(messageClass == 'message received'){
	        			  html += `
	  			            <div class='${"${messageClass}"}'>
	  			                <div class="message-avatar" style="background-image: url(${'${friendHeadimg}'})">
	  			                </div>
	  			                <div class="message-content">
	  			                    <div class="message-name">${"${chatRecord.myAccount}"}</div>
	  			                    <div class="message-bubble">${"${chatRecord.message}"}</div>
	  			                    <div class="message-time">${"${chatRecord.messageDate}"}</div>
	  			                </div>
	  			            </div>`;
	        		  }
			       
			        $('#chat-messages').html(html);
	        	  }
	        	  
	        	  scrollToBottom();
	           
	          };

	}
	function ws_sendMsg(){
		
		var msg = $("#message-input").val();
		
		let data={
					myAccount:me,
					friendAccount:friendAccount,
					message:msg
				}
		console.log(JSON.stringify(data));
		var jsonStr = JSON.stringify(data);
		ws.send(jsonStr);
		$("#message-input").val("");
	}
	function ws_sendImg(){
		
	}	
	</script>
<!-- 实时添加动态 -->
<script>
var ws_dy ="";
//let ip = "localhost:8080";//测试时使用，实际使用需要用服务器ip
var ws_dy_url = "ws://localhost:8080/chatBlog/insertdynamics/${sessionScope.loginUser.account}";
function ws_send_dynamics(){
	send_dynamics();
	console.log(123)
}
ws_connect_dy();
/* $(function(){
	//页面加载后，获取一个 websocket连接
	ws_connect_dy();
}); */
function ws_connect_dy(){
         if ('WebSocket' in window) {
        	 ws_dy = new WebSocket(ws_dy_url);
         } else if ('MozWebSocket' in window) {
        	 ws_dy = new MozWebSocket(ws_dy_url);
         } else {
             Console.log('Error: WebSocket is not supported by this browser.');
             return;
         }

         ws_dy.onopen = function () {
        	 console.log(ws_dy_url);
             console.log('Info: WebSocket connection opened.'+"dy打开了");
             
         };

         ws_dy.onclose = function () {
              console.log('Info: WebSocket closed.'+"dy关闭了");
          };

          ws_dy.onmessage = function (message){
        	  let dynamic = JSON.parse(message.data);
        	  console.log(dynamic);
        	  var newFeed = `
                  <div class="feed-item">
                      <div class="feed-header">
                          <div class="feed-avatar-container">
                              <img src='${"${dynamic.userheadimg}"}' alt="头像" class="feed-avatar">
                              <div class="status-badge online"></div>
                          </div>
                          <div class="feed-user">
                              <h4>${"${dynamic.nickname}"} <span class="feed-meta">更新了</span></h4>
                              <span class="time">${"${dynamic.dyTime}"} <i class="fas fa-globe-americas"></i></span>
                          </div>
                          <div class="feed-actions">
                              <button class="feed-more" data-tooltip="更多">
                                  <i class="fas fa-ellipsis-h"></i>
                              </button>
                          </div>
                      </div>
                      <div class="feed-content">
                          <p>${"${dynamic.sendText}"}</p>
                          <c:if test="${dynamic.dynamicsImage}!=null">
                      		<img src="${dynamic.dynamicsImage}" alt="图片">
                      	</c:if>
                      </div>
                      <div class="feed-footer">
                          <div class="feed-stats">
                              <div class="likes-count">
                                  <i class="far fa-thumbs-up"></i>
                                  <span class="likedyNum"></span>
                                  <div id="likenikenameAll" class="likenikenameAll">
                              		<span class="nicknames"></span>
                              		</div>
                              </div>
                              <div class="dynamics_id">${dynamic.dynamicsId}</div>
                              <div class="comments-count">
                                  <span>0条评论</span>
                              </div>
                          </div>
                          <div class="feed-buttons">
                              <button class="like-btn" onclick="getlike.call(this)" data-id=${"${dynamic.dyTime}"}>
                                  <i class="far fa-thumbs-up"></i> 赞
                              </button>
                                <input type="text" class="comment-input" placeholder="发表评论" name="comment_text">
                                  <!-- 评论按钮 -->
                        		<button class="comment-btn">评论</button>
                                  
                        	</div>
                        	 <!-- 评论列表 -->
                     		<div class="comment-list">
                          </div>
                      </div>
                  </div>
              `;
  			 // 添加到列表顶部
              $('.feed-list').prepend(newFeed);
              // 重置表单
              var $btn = $(this);
             	$('.post-box textarea').val('');
              $btn.html('<i class="fas fa-paper-plane"></i> 发表');
              $btn.prop('disabled', false);
              
              // 滚动到新动态
              $('html, body').animate({
                  scrollTop: $('.feed-list .feed-item:first').offset().top - 20
              }, 500);
              
  			}
}
function send_dynamics(){
	
	let mysendtext = $("#mysendtext").val();

	let data={
			nickname:nickName,
			accounts:me,
			userheadimg:myHeadimg,
			sendText:mysendtext
			}
	console.log(JSON.stringify(data));
	var jsonStr = JSON.stringify(data);
	ws_dy.send(jsonStr);
	$("#mysendtext").val("");
}
function ws_sendImg(){
	
}
</script>
<body>
<div id="qq-app">
<!-- 左侧导航栏 -->
<div id="sidebar">
    <div class="nav-item" data-page="My_headimg">
        <div class="avatar headerImg" style="background-image: url(${loginUser.avatar});margin:auto;">
        <%-- <img src="${loginUser.avatar}"   class="headimg"> --%>
        </div>
    </div>

    <div class="nav-item active" data-page="message" id="messagepage">
        <div class="nav-icon"><i class="fas fa-comment-alt"></i></div>
        <div class="nav-text">消息通知</div>
    </div>
    
    <div class="nav-item" data-page="contact">
        <div class="nav-icon"><i class="fas fa-user-friends"></i></div>
        <div class="nav-text">联系人</div>
    </div>
    <div class="nav-item" data-page="moment">
        <div class="nav-icon"><i class="fas fa-newspaper"></i></div>
        <div class="nav-text">动态</div>
    </div>
    <div class="nav-item" data-page="wallet">
        <div class="nav-icon"><i class="fas fa-wallet"></i></div>
        <div class="nav-text" id="shop">购物</div>
    </div>
</div>

<!-- 主内容区 -->
<div id="main-content">
	
    <!-- 顶部工具栏 -->
    <div id="toolbar">
        <div class="logo">QQ</div>
        <div id="search-box">
            <i class="fas fa-search search-icon"></i>
            <form action="insertFriend.do" method="POST" id="insertFriend">
	            <input id="search-input" type="text" placeholder="搜索" name="account"></input>
           	</form>
           	<div class="selectUser-head">
                        
            </div>
        </div>
        
       	<!-- 未读消息 -->
        <div class="tool-icon"><i class="fas fa-plus-circle"></i></div>
        <div class="tool-icon">
            <i class="fas fa-bell"></i>
            <span class="badge">3</span>
        </div>
        <div class="tool-icon"><i class="fas fa-user-circle"></i></div>
    </div>
    
    <!-- 内容区 -->
    <div id="content-area">
        <!-- 消息/联系人列表 -->
       
        <div id="contact-list">
           <!-- 消息通知 -->
			<div id="message-list" class="contact-list" style="display:none;">
			    <div class="message-contact-group">
			        <div class="group-title">
			            <span>消息通知</span>
			            <i class="fas fa-chevron-down"></i>
			        </div>
			        <div id="messageContainer">
			        	<c:forEach items="${sessionScope.addFriend}" var="addf">
			        		
			        			<div class="newHaoYou" data-user="${addf.getFriendaccount()}" data-avatar="${addf.firendsavater}">
				              	<div class="contact-avatar avatar" style="background-image: url(${addf.firendsavater});">
				              		${addf.getFirendNickname()}
				              	</div>
					              <div class="contact-info">
					                  <div class="contact-name">${addf.friendaccount}</div>
					                  <div class="contact-lastmsg"></div>
					                  <button class="contact-enevt2" ${addf.getFriendaccount() != sessionScope.loginUser.account ? 'style="display:none;"' : ''} id="addFriend">添加</button>
            						  <button class="contact-enevt2" ${addf.getFriendaccount() != sessionScope.loginUser.account ? 'onclick="delectFriend(this)"' : 'style="display:none;"'}>删除</button>
					                  <button class="contact-enevt2" ${addf.getFriendaccount() == sessionScope.loginUser.account ? 'style="display:none;"' : ''} id="addFriend">添加</button>
					                  <!-- <button class="contact-enevt2" id="addFriend">添加</button>
					                  <button class="contact-enevt2" onclick="delectFriend(this)">删除</button> -->
			              			</div>
			      				</div>
			        	</c:forEach>
			        </div> <!-- 动态加载消息内容 -->
			    </div>
			</div>
            <!-- 好友列表 -->
            <div class="contact-group">
                <div class="group-title collapsed">
                    <span>好友</span>
                    <i class="fas fa-chevron-down"></i>
                </div>
                
                	<div id="friendListContainer"></div> <!-- 动态内容渲染到这里 -->
                <%-- console.log(${myFriends}); --%>
			                <c:forEach items="${myFriends}" var="myfriend" >
			                	
			                	<div class="contact-item" data-user="${myfriend.getFriendaccount()}" data-avatar="${myfriend.firendsavater}"  onclick="openChatWindow(this)">
			                        <div class="contact-avatar avatar" style="background-image: url(${myfriend.firendsavater});">${myfriend.getFirendNickname()}
			                        
			                        </div>
			                        <div class="contact-info">
			                            <div class="contact-name">${myfriend.getFirendNickname()}</div>
			                            <div class="contact-lastmsg">在线</div>
			                        </div>
			                    </div> 
			                
			                </c:forEach>
                
            	</div>
            
            
        
        
        <div id="chat-container">
             <div id="chat-header">
                <div class="chat-title">与 聊天中</div>
                <div class="chat-actions">
                    <i class="fas fa-phone-alt"></i>
                    <i class="fas fa-video"></i>
                    <i class="fas fa-ellipsis-h"></i>
                    <i class="fas fa-times close-chat"></i>
                </div>
            </div>
            <div id="chat-messages">
                
            </div>
            <div id="chat-input-area">
                <textarea id="message-input" placeholder="输入消息..."></textarea>
                <div class="chat-toolbar">
                </div>
            </div>
        </div>
        
        
        
        
        
        
    <!-- 动态页面 -->
                <div id="moment-page">
        <div class="main-content">
<!-- 左侧边栏 -->
<div class="left-sidebar">
    <div class="profile-card">
        <div class="profile-bg" style="background-image: url('../img/qqspaceimg/微信图片_20250606105148.jpg')">
            <div class="bg-overlay"></div>
        </div>
        <div class="profile-info">
            <div class="avatar-container">
               <img src="${loginUser.avatar}" alt="头像" class="profile-avatar">
                <div class="status-badge online"></div>
            </div>
            <h3>${loginUser.nickName}</h3>
            <p class="profile-desc">生活不止眼前的苟且，还有诗和远方~</p>
        	<div class="stats" style:"display:none">
                <div class="stat-item">
                    <span class="number"></span>
                    <span class="label"></span>
                </div>
                <div class="stat-item">
                    <span class="number"></span>
                    <span class="label"></span>
                </div>
                <div class="stat-item">
                    <span class="number"></span>
                    <span class="label"></span>
                </div>
            </div>
        </div>
        <div class="profile-actions">
            <button class="btn btn-primary btn-edit">
                <i class="fas fa-pencil-alt"></i> 
            </button>
            <button class="btn btn-secondary btn-vip">
                <i class="fas fa-crown"></i> 
            </button>
        </div>
    </div>
 
    <div class="sidebar-module">
        <div class="module-header">
            <i class="fas fa-calendar-alt"></i>
            <h3>最近访客</h3>
            <a href="#" class="view-all">查看全部</a>
        </div>
        <div class="visitors-grid">
           
        </div>
    </div>
</div>


<div class="content-area">
    <!-- 发表动态 -->
    <div class="post-box">
        <div class="post-header">
          <img src="${loginUser.avatar}" alt="头像" class="post-avatar">
            <textarea placeholder="分享你的新鲜事..." rows="3" name="mysendtext" id="mysendtext"></textarea>
        </div>
        <input type="file" name="dyImg" accept="image/*" id="dyImg"> 
			<!-- img用于预览 用户上传的图片 -->
		
			<img src=""  id="avatar" display="none">
        <div class="post-toolbar">                                  
            <button class="post-btn" onclick="ws_send_dynamics()">
                <i class="fas fa-paper-plane"></i> 发表
            </button>
        </div>
    </div>

    <!-- 动态列表 -->
    <div class="feed-list">
        <c:forEach items="${dynamicsAll}" var="dynamic">
        	<div class="feed-item">
               <div class="feed-header">
                   <div class="feed-avatar-container">
                       <img src="${dynamic.userheadimg}" alt="头像" class="feed-avatar">
                       <div class="status-badge online"></div>
                   </div>
                   <div class="feed-user">
                        <h4>${dynamic.nickname} <span class="feed-meta">更新了状态</span></h4>
                        <span class="time">${dynamic.dyTime}<i class="fas fa-globe-americas"></i></span>
                    </div>
                    <div class="feed-actions">
                    </div>
                </div>
                <div class="feed-content">
                    <p>${dynamic.sendText}</p>
                    <c:if test="${dynamic.dynamicsImage}!=null">
                    	<img src="${dynamic.dynamicsImage}" alt="图片">
                    </c:if>
                </div>
                <div class="feed-footer">
                    <div class="feed-stats">
                        <div class="likes-count">
                            <i class="far fa-thumbs-up"></i>
                            <span class="likedyNum"></span>
                            <div id="likenikenameAll" class="likenikenameAll">
                            	<span class="nicknames"></span>
                            </div>
                        </div>
                        <div class="dynamics_id">${dynamic.dynamicsId}</div>
                        <div class="comments-count">
                        </div>
                    </div>
                    <div class="feed-buttons">
                        <button class="like-btn" onclick="getlike.call(this)" data-id=${dynamic.dynamicsId}>
                            <i class="far fa-thumbs-up"></i> 赞
                        </button>  
                        <input type="text" class="comment-input" placeholder="发表评论" name="comment_text">
                              <!-- 评论按钮 -->
                    	<button class="comment-btn">评论</button>                                   
                    </div>
                     <!-- 评论列表 --> 
                    	<div class="comment-list">
                   	 	</div>
                </div>
            </div>
        </c:forEach>
	</div>

<!-- 右侧边栏 -->
<div class="right-sidebar">
    
    </div>

    <div class="sidebar-module">
        
	</div>
</div>
        
        <!-- 钱包页面 -->
        <div id="wallet-page">
            <div class="wallet-header">
                <div class="wallet-title">QQ钱包</div>
                <i class="fas fa-times close-page"></i>
            </div>
            
            <div class="wallet-card">
                <div class="wallet-balance">余额 (元)</div>
                <div class="wallet-amount">8,523.64</div>
                <div class="wallet-actions">
                    <div class="wallet-action">
                        <i class="fas fa-money-bill-wave"></i>
                        <span>充值</span>
                    </div>
                    <div class="wallet-action">
                        <i class="fas fa-hand-holding-usd"></i>
                        <span>提现</span>
                    </div>
                    <div class="wallet-action">
                        <i class="fas fa-exchange-alt"></i>
                        <span>转账</span>
                    </div>
                </div>
            </div>
            
            <div class="wallet-section">
                <div class="wallet-section-title">常用功能</div>
                <div class="wallet-features">
                    <div class="wallet-feature">
                        <i class="fas fa-mobile-alt"></i>
                        <div class="wallet-feature-name">手机充值</div>
                    </div>
                    <div class="wallet-feature">
                        <i class="fas fa-bolt"></i>
                        <div class="wallet-feature-name">生活缴费</div>
                    </div>
                    <div class="wallet-feature">
                        <i class="fas fa-subway"></i>
                        <div class="wallet-feature-name">交通出行</div>
                    </div>
                    <div class="wallet-feature">
                        <i class="fas fa-credit-card"></i>
                        <div class="wallet-feature-name">信用卡还款</div>
                    </div>
                </div>
            </div>
            
            <div class="wallet-section">
                <div class="wallet-section-title">理财服务</div>
                <div class="wallet-features">
                    <div class="wallet-feature">
                        <i class="fas fa-piggy-bank"></i>
                        <div class="wallet-feature-name">理财通</div>
                    </div>
                    <div class="wallet-feature">
                        <i class="fas fa-shield-alt"></i>
                        <div class="wallet-feature-name">保险服务</div>
                    </div>
                    <div class="wallet-feature">
                        <i class="fas fa-coins"></i>
                        <div class="wallet-feature-name">基金</div>
                    </div>
                    <div class="wallet-feature">
                        <i class="fas fa-chart-line"></i>
                        <div class="wallet-feature-name">股票</div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- 个人资料 -->
<div id="headclickfct">
    <div class="head_homepage">
        <div class="qq-container">
        <div class="qq-header">
            <div class="qq-avatar" >
                <img src="${sessionScope.loginUser.avatar}">
                <div class="qq-level">VIP7</div>
            </div>
            <div class="qq-info">
                <h1>${sessionScope.loginUser.nickName}</h1>
                <p>QQ号：${sessionScope.loginUser.account}</p>
                <p>个性签名：生活不止眼前的苟且，还有诗和远方~</p>
                <div class="qq-tags">
                    <span><i class="fas fa-sun"></i> 阳光</span>
                    <span><i class="fas fa-user-clock"></i> 90后</span>
                    <span><i class="fas fa-basketball-ball"></i> 运动</span>
                </div>
            </div>
        </div>
        
        <div class="qq-nav">
            <ul>
                <li class="active"><i class="fas fa-user"></i> 资料</li>
                <li><i class="fas fa-images"></i> 相册</li>
                <li><i class="fas fa-comment"></i> 说说</li>
            </ul>
        </div>
        
        <div class="qq-content">
            <div class="qq-profile">
                <div class="profile-section">
                    <h3><i class="fas fa-id-card"></i> 基本资料</h3>
                    <div class="profile-row">
                        <span>性别：男</span>
                        <span>年龄：25岁</span>
                        <span>生日：1月1日</span>
                        <span>星座：摩羯座</span>
                    </div>
                    <div class="profile-row">
                        <span>地区：北京 朝阳区</span>
                        <span>职业：前端工程师</span>
                        <span>学校：清华大学</span>
                        <span>家乡：上海</span>
                    </div>
                </div>
                
                <div class="profile-section">
                    <h3><i class="fas fa-heart"></i> 兴趣爱好</h3>
                    <div class="profile-row">
                        <span>音乐：流行、摇滚、电子</span>
                        <span>电影：科幻、动作、悬疑</span>
                    </div>
                    <div class="profile-row">
                        <span>运动：篮球、游泳、健身</span>
                        <span>书籍：科幻小说、心理学</span>
                    </div>
                </div>
                
                <div class="profile-section">
                    <h3><i class="fas fa-chart-line"></i> QQ等级</h3>
                    <div class="qq-level-progress">
                        <div class="progress-bar" style="width: 65%;"></div>
                        <span>65级 (12345天)</span>
                    </div>
                    <div class="profile-row" style="margin-top: 15px;">
                        <span>成长值：6500/10000</span>
                        <span>升级还需：3500成长值</span>
                    </div>
                </div>
                
                <div class="profile-section">
                    <h3><i class="fas fa-star"></i> 个人荣誉</h3>
                    <div class="profile-row">
                        <span>QQ空间达人</span>
                        <span>连续登录365天</span>
                    </div>
                </div>
            </div>
            
            <div class="qq-sidebar">
                <div class="sidebar-section">
                    <h3><i class="fas fa-users"></i> 好友动态</h3>
                    <ul class="qq-feed">
                        <li>
                            <img src="../img/headimg/1.jpg" alt="好友头像">
                            <div class="feed-content">
                                <p><strong>小红</strong> 更新了状态</p>
                                <p>今天天气真好，出去郊游了~ 拍了好多美美的照片！</p>
                                <p class="feed-time">2小时前</p>
                            </div>
                        </li>
                        <li>
                            <img src="../img/headimg/1.jpg" alt="好友头像">
                            <div class="feed-content">
                                <p><strong>小刚</strong> 上传了新照片</p>
                                <p>周末聚餐的照片，大家看看~ 这家餐厅的环境和菜品都很不错！</p>
                                <p class="feed-time">昨天 18:30</p>
                            </div>
                        </li>
                        <li>
                            <img src="../img/headimg/1.jpg" alt="好友头像">
                            <div class="feed-content">
                                <p><strong>小李</strong> 分享了音乐</p>
                                <p>推荐一首最近单曲循环的歌：《起风了》真的太好听了！</p>
                                <p class="feed-time">前天 22:15</p>
                            </div>
                        </li>
                    </ul>
                </div>
                
                <div class="sidebar-section">
                    <h3><i class="fas fa-trophy"></i> 最近成就</h3>
                    <ul class="qq-achievements">
                        <li><i class="fas fa-medal"></i> 连续登录30天</li>
                        <li><i class="fas fa-medal"></i> 空间访问量突破1000</li>
                        <li><i class="fas fa-medal"></i> 发表第50条说说</li>
                    </ul>
                </div>
            </div>
        </div>
        
        <div class="qq-footer">
            <p>© 2023 QQ个人主页 | <a href="#">隐私政策</a> | <a href="#">关于QQ</a> | <a href="#">帮助中心</a></p>
        </div>
    </div>
    </div>
</div>
<form action="updateavatarImg.do" style="display: none" enctype="multipart/form-data">
	<input type="file" id="inputImg">
</form>


<!-- 全屏按钮 -->
<div id="fullscreen-btn">
    <i class="fas fa-expand"></i>
</div>
</div>

<script src="${pageContext.request.contextPath}/js/jquery.js"></script>
<script src="${pageContext.request.contextPath}/js/qq.js"></script>
<script src="${pageContext.request.contextPath}/js/personal_data.js"></script>
</body>
<script>
//查询评论
// 获取所有动态ID元素
var elements = document.querySelectorAll('.dynamics_id');
var comment_List = document.querySelectorAll('.comment-list');
var textContents = Array.from(elements).map(el => el.textContent.trim());
for(var i=0;i<textContents.length;i++){
	var dynamics_id = textContents[i];
	var index = i;
	selectComment(dynamics_id,index);
}
function selectComment(dynamics_id,index){
	$.ajax({
			url:"/chatBlog/CommentSelect.do",
			type:"POST",
			data:{
				dynamics_id:dynamics_id
			},success:function(data){
				let allcomment = JSON.parse(data);
				let Listcomment = allcomment.comments;
				let cnickName = allcomment.nickName;
				for(var i=0;i<Listcomment.length;i++){
		            var onecomment = Listcomment[i];
		/*             console.log(onecomment); */
		            var p = $("<p>").addClass("profile-desc").text(cnickName+":"+onecomment);
		            $(comment_List[index]).append(p);
				}
			} 
	})
} 
//发布评论
$(document).ready(function() {
    // 评论按钮点击事件
    $('.comment-btn').click(function() {
        var $feedItem = $(this).closest('.feed-item');
        var commentText = $feedItem.find('.comment-input').val();
        var dynamics_id = $feedItem.find('.dynamics_id').text();
    /*     console.log(commentText); */
        if (commentText.trim() === '') {
            return;
        }
        $.ajax({
            url: "/chatBlog/Comment.do",
            type:"POST",
            data:{
            	dynamics_id: dynamics_id,
                user_id:user_id,
                commentText: commentText
            },
            success: function(response) {
                if (response) {
                    // 评论成功，将评论添加到评论列表
                   var commentList = $feedItem.find('.comment-list');
                   var p = $("<p>").addClass("profile-desc").text(nickName+":"+commentText);
                  	commentList.append(p);
                  	$feedItem.find('.comment-input').val("");
                   /*  $feedItem.find('.comment-input').val(''); */
                }else {
                    alert('评论失败，请稍后重试');
                }
            },
            error: function() {
                alert('网络错误，请稍后重试');
            }
        });
    });
});
//JavaScript
//点赞个数记录
/* var elements = document.querySelectorAll('.dynamics_id'); */
var likeElements = document.querySelectorAll('.likedyNum');
/* var textContents = Array.from(elements).map(el => el.textContent.trim()); */
/* console.log('所有动态内容:', textContents); */
for(var i=0;i<textContents.length;i++){
	var dynamics_id = textContents[i];
	var index = i;
	allDynamicsLike(dynamics_id,index);
	alldyLikeNickname(dynamics_id,index)
}
function allDynamicsLike(dynamics_id,index){
	$.ajax({
			url:"/chatBlog/LikeDynamicsNum.do",
			type:"POST",
			data:{
				dynamics_id:dynamics_id
			},success:function(data){
				let ThislikeNum = JSON.parse(data);
				 if (index < likeElements.length) {
			            $(likeElements[index]).text(ThislikeNum);
			         }
/* 				 console.log("dz"+ThislikeNum); */
			}
	})
}
//点赞用户记录
var likenikenameAll = document.querySelectorAll('.likenikenameAll')
/* var nicknameElements = document.querySelectorAll('.nicknames'); */
function alldyLikeNickname(dynamics_id,index){
	$.ajax({
		url:"/chatBlog/allNikename.do",
		type:"POST",
		data:{
			dynamics_id:dynamics_id
		},success:function(data){
			let AllnickName = JSON.parse(data);
			 for (var i=0 ;i< AllnickName.length;i++) {
		          /* $(nicknameElements[index]).text(AllnickName[i]); */
		          var dyallnickname = $("<span>").text(AllnickName[i]+" | ");
		         $(likenikenameAll[index]).append(dyallnickname);
		         }
/* 				 console.log("dz"+ThislikeNum); */
		}
	})
}
</script>

<script>
var friendAccount = "";
var friendHeadimg = "";
function openChatWindow(element) {
    // 获取好友账号
    friendAccount = element.getAttribute('data-user');
    friendHeadimg = element.getAttribute('data-avatar');
    var chatContainer = document.getElementById('chat-container');
    // 显示聊天窗口（之前隐藏的话）
    chatContainer.style.display = 'block';
    $("#chat-container").addClass("show");
    var myAccount = me;
   
    selecOurmsg(me,friendAccount);
}

function selecOurmsg(me,friendAccount){
	$.ajax({
		url:"/chatBlog/ChatrecordServlet.do",
		type:"POST",
		data:{
			myAccount:me,
			friendAccount:friendAccount
		},
		success: function(data) {
			console.log("-----------");
		    let html = '';
		    //const me = '这里替换成当前用户实际账号'; 
		    for (let i = 0; i < data.length; i++) {
		        //console.log(${data[i].myAccount});
		        let messageClass = data[i].myAccount === me 
		            ? 'message sent' 
		            : 'message received';
		        html += `
		            <div class='${"${messageClass}"}'>
		                <div class="message-avatar" style="background-image: url(${'${friendHeadimg}'})">
		                	
		                </div>
		                <div class="message-content">
		                    <div class="message-name">${"${data[i].myAccount}"}</div>
		                    <div class="message-bubble">${"${data[i].message}"}</div>
		                    <div class="message-time">${"${data[i].messageDate}"}</div>
		                </div>
		            </div>
		        `;
		        console.log(${data[i].myAccount});
		    }
		    $('#chat-messages').html(html);
		}
	})
	}
function scrollToBottom() {
	  const chatMessages = document.getElementById("chat-messages");
	  chatMessages.scrollTop = chatMessages.scrollHeight;
	}

</script>
<script>
$("#insertFriend").submit(function(e){
	e.preventDefault();
})
$("#search-input").on("input",function(){
	let account = $("#search-input").val();
	if(account!=""){
		setTimeout(function(){
			$.ajax({
				url:"/chatBlog/selectFriend.do",
				type:"POST",
				data:{
					account:account,
					me:me
				},
				success:function(data){
					let users = JSON.parse(data);
					let container = $(".selectUser-head"); 
					container.html("");
					container.css("display","block");
		            // 3. 模板字符串拼接
		            users.forEach(function(user){
		            	let friendItem = $("<div>").addClass("friend-item");
		            	let fHeadimg = $("<img>").addClass("headimg").attr("src",user.avatar);
		            	let account = $("<span>").addClass("account").text(user.account);
		            	let nickname = $("<span>").addClass("nickname").text(user.nickName);
		            	let addFriend = $("<button>").addClass("addFriend").text("添加");
		            	
		            	//点击添加用户
		            	addFriend.click(function(){
		            		$("#search-input").val("");
		            		$("#search-input").html("");
		            		insertFriend(user);
		            		container.css("display","none");
		            	})
		            	
		            	friendItem.append(fHeadimg,account,nickname,addFriend);
		            	container.append(friendItem);
		            });
		           
				}
			},200);
		});
	}else{
		let container = $(".selectUser-head").css("display","none");
	}
});

//添加用户



var ws2 ="";
var ws2_url = "ws://localhost:8080/chatBlog/InsertFriend/${sessionScope.loginUser.account}";

ws_addfri();
/* $(function(){
	//页面加载后，获取一个 websocket连接
	ws_connect();
}); */

let insertFriend = function(user){
	var insertRow = 0;
	let data={
			myaccount:me,
			friendaccount:user.account,
			firendsavater:user.avatar,
			firendNickname:user.nickName,
			
		}
	console.log(JSON.stringify(data));
	var jsonStr = JSON.stringify(data);
	ws2.send(jsonStr);

}
function ws_addfri(){

         if ('WebSocket' in window) {
             ws2 = new WebSocket(ws2_url);
         } else if ('MozWebSocket' in window) {
             ws2 = new MozWebSocket(ws2_url);
         } else {
             Console.log('Error: WebSocket is not supported by this browser.');
             return;
         }

         ws2.onopen = function () {
             console.log('Info: WebSocket connection opened.');
             
         };

         ws2.onclose = function () {
              console.log('Info: WebSocket closed.');
          };

          ws2.onmessage = function (message) {
        	  
        	  let messag =message.data;
        	  let msg = JSON.parse(messag);
        	  console.log(msg);
        	  let addFriend = $('#messageContainer').html();
        	  console.log(msg.friendaccount);
        	  if(msg.friendaccount != me){
        		  addFriend += `
  		        	<div class="newHaoYou" data-user=${"${msg.friendaccount}"} data-avatar=${"${msg.firendsavater}"}>
  		              	<div class="contact-avatar avatar" style="background-image: url(${"${msg.firendsavater}"});">${"${msg.friendaccount}"}
  		              
  		              	</div>
  		              <div class="contact-info">
  		                  <div class="contact-name">${"${msg.friendaccount}"}</div>
  		                  <div class="contact-lastmsg"></div>
  		                  <button class="contact-enevt2">已添加</button>
  		              </div>
  		      		</div> `
        	  }else{
        		  addFriend += `
        	  	
		        	<div class="newHaoYou" data-user=${"${msg.friendaccount}"} data-avatar=${"${msg.firendsavater}"}>
		              		<div class="contact-avatar avatar" style="background-image: url(${"${msg.firendsavater}"});">${"${msg.friendaccount}"}
		              
		              		</div>
			            	<div class="contact-info">
			                  <div class="contact-name">${"${msg.friendaccount}"}</div>
			                  <div class="contact-lastmsg"></div>
			                  <button class="contact-enevt2" id="addFriend">添加</button>
			                  <button class="contact-enevt2" onclick="delectFriend(this)">删除</button>
			              	</div>
			      	</div> `
		    	 
        	  }
        	  $("#messageContainer").html(addFriend);
	      		alert("你成功添加此用户");
          };

}
$('#messageContainer').on('click', '.newHaoYou .contact-enevt2[id="addFriend"]', function() {
    // 获取 data-user 的值
    let dataUser = $(this).closest('.newHaoYou').data('user'); 
    // 获取 .newHaoYou 这个 div（closest 从当前元素往上找最近的匹配元素）
    let newHaoYouDiv = $(this).closest('.newHaoYou'); 

    console.log('data-user 的值：', dataUser);
    console.log('newHaoYou 容器：', newHaoYouDiv);
	console.log(me);
    addFriend(dataUser, newHaoYouDiv); 
  });
function addFriend(friendaccount,newHaoYouDiv){
	$.ajax({
		url:"/chatBlog/addFriend.do",
		type:"POST",
		data:{
			myaccount:me,
			friendAccount:friendaccount,
		},
		success: function(data) {
			let friendUser = JSON.parse(data);
			//console.log(dom)
			//let haoyouDiv = $(dom).closest('.newHaoYou');
			//console.log(haoyouDiv);
			newHaoYouDiv.remove(); 
			
			let adfriend = $("#friendListContainer").html();
			adfriend += `
				<div class="contact-item" data-user=${"${friendUser.account}"} data-avatar=${"${friendUser.avatar}"}  onclick="openChatWindow(this)">
                <div class="contact-avatar avatar" style="background-image: url(${'${friendUser.avatar}'});">${"${friendUser.nickName}"}
                
                </div>
                <div class="contact-info">
                    <div class="contact-name">${"${friendUser.nickName}"}</div>
                    <div class="contact-lastmsg">在线</div>
                </div>
            </div> 
			`;
			alert("你成功添加此用户");
			$("#friendListContainer").html(adfriend);
		}
	})
}

$(".qq-avatar>img").click(function(){
	$("#inputImg").click();
})
$("#inputImg").change(function(e){
	let file = this.files[0];
	let reader = new FileReader();
	reader.onload = function(e){
		$(".headerImg").attr("src",e.target.result);
		$(".qq-avatar>img").attr("src",e.target.result);

	}
	let formData = new FormData();
	formData.append("inputImg",file);
	$.ajax({
		type:"POST",
		url:"updateavatarImg.do",
		data:formData,
		contentType: false,
		processData: false,
		success:function(data){
			if(data){
				alert("修改成功");
				$(".headerImg").attr("src",e.target.result);
				$(".qq-avatar>img").attr("src",e.target.result);
			}else{
				alert("修改失败");
			}
		}
	});
	reader.readAsDataURL(file);
});
function delectFriend(dom,friendaccount){
	$.ajax({
		type:"POST",
		url:"deletaddFriend.do",
		data:{
			myAccount:me,
			friendAccount:friendaccount,
		},
		success: function(data) {
			let friendUser = JSON.parse(data);
			if(friendUser = 1){
				let haoyouDiv = $(dom).closest('.newHaoYou');
				console.log(haoyouDiv);
				haoyouDiv.remove(); 
			}
			
		}
	});
	
	
}
</script>
<script>
document.getElementById("dyImg").addEventListener("change",function(event){
	let file = event.target.files[0];
	console.log(file);
	if(file){
		let reader = new FileReader();
		reader.onload = function(e){
			document.getElementById("avatar").src=e.target.result;
		}
		reader.readAsDataURL(file);
	}
})
function fileDy(){
	var dyImg = $('#dyImg').prop('files');
	 var data = new FormData();
	 data.append('dyImg', dyImg[0]);
	 $.ajax({
	  url: "/chatBlog/ReleaseDy.do",
	  type: "POST",
	  data: {
		  dyImg:dyImg
	  },
	  cache: false,
	  processData: false,
	  contentType: false
	 });
}
//点赞添加数据删除数据
function getlike(){
    var $btn = $(this);
    var $likes = $btn.closest('.feed-footer').find('.likedyNum');
    var $likedyName = $btn.closest('.feed-footer').find('#likenikenameAll');
    var currentLikes = parseInt($likes.text());
    var nickname = $("<span>").addClass("likedyName").text(nickName);
    var mynickname = $btn.closest('.feed-footer').find('.likedyName');
    var nicknamebox = $btn.closest('.feed-footer').find('.nicknames');
    console.log(nickname);
    if ($btn.hasClass('liked')) { 
    	mynickname.remove();
    	 nicknamebox.text(nickName).remove();
    	 let dynamics_id = $btn.data('id');
 			$.ajax({
 			url:"/chatBlog/deletLike.do",
 			type:"POST",
 			data:{
 				user_id:user_id,
 				dynamics_id:dynamics_id
 			},success:function(data){
 				let deletelike = JSON.parse(data);				
 			}
 		});
        $btn.removeClass('liked');
        $btn.find('i').removeClass('fas').addClass('far');
        $likes.text(currentLikes - 1);
    }else{
    	$likedyName.append(nickname);
    	let dynamics_id = $btn.data('id');
    	console.log(user_id);
    	console.log(dynamics_id);
    		$.ajax({
    			url:"/chatBlog/likedynamics.do",
    			type:"POST",
    			data:{
    				user_id:user_id,
    				dynamics_id:dynamics_id
    			},success:function(data){
    				let likedys = JSON.parse(data);				
    			}
    		});
        $btn.addClass('liked');
        $btn.find('i').removeClass('far').addClass('fas');
        $likes.text(currentLikes + 1);       
        // 添加动画效果
        $btn.find('i').css('transform', 'scale(1.5)');
        setTimeout(function() {
            $btn.find('i').css('transform', 'scale(1)');
        }, 300);
    }
}
</script>
<!-- 购物跳转 -->
<script>
	$("#shop").click(function(){
		window.open("/chatBlog/MainView/index.jsp");
	})
</script>
</html>